package com.training.api.controller;

import com.training.api.repository.AudioRepository;
import com.training.api.service.AuthorizationService;
import com.training.bean.Audio;
import com.training.jwt.JWTUtils;
import com.training.utils.UrlUtils;
import com.training.base.Result;
import com.training.bean.CourseStage;
import com.training.bean.Course;
import com.training.bean.CourseContent;
import com.training.api.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/course")
public class CourseController {
    @Autowired
    private CourseService service;
    
    @Autowired
    private AuthorizationService authorizationService;
    @Autowired
    private AudioRepository audioRepository;

    /**
     * 获取所有课程阶段（供移动端使用）
     * @param request HTTP请求对象
     * @return 课程阶段列表结果
     */
    @GetMapping("/getAllStage")
    public ResponseEntity<Result<List<CourseStage>>> getAllStage(HttpServletRequest request) {
        try {
            List<CourseStage> datas = service.getAllStage();
            if (datas != null){
                // 为每个课程阶段动态构建完整封面URL
                List<CourseStage> stagesWithFullCoverUrls = datas.stream()
                    .map(stage -> {
                        if (stage.getCover() != null && !stage.getCover().isEmpty()) {
                            stage.setCover(UrlUtils.buildFullUrl(request, stage.getCover()));
                        }
                        return stage;
                    })
                    .collect(Collectors.toList());
                return ResponseEntity.ok(new Result<>(stagesWithFullCoverUrls, true, "获取课程阶段成功"));
            }else {
                return ResponseEntity.status(500).body(Result.fail(500, "获取课程阶段失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Result.fail(500, "获取课程阶段失败: " + e.getMessage()));
        }
    }

    /**
     * 获取指定阶段的所有课程（供移动端使用）
     * @param csid 课程阶段ID
     * @param request HTTP请求对象
     * @return 课程列表结果
     */
    @GetMapping("/getAllCourse")
    public ResponseEntity<Result<List<Course>>> getAllCourse(@RequestParam int csid, HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userId = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userId == -1) {
                return ResponseEntity.status(401).body(Result.fail(401, "无法获取用户身份信息"));
            }
            
            // 从JWT token中获取用户类型
            String userType = JWTUtils.getUserTypeFromRequest(request);
            boolean isAuthorized= authorizationService.isUserAuthorizedForStage(userId,userType, csid);
            if (!isAuthorized) {
                return ResponseEntity.status(403).body(Result.fail(403, "未授权访问该课程内容"));
            }
            
            List<Course> datas = service.getCoursesWithCollectAndProgress(csid, userId);
            if (datas != null){
                // 为每个课程动态构建完整封面URL
                List<Course> coursesWithFullCoverUrls = datas.stream()
                    .map(course -> {
                        if (course.getCover() != null && !course.getCover().isEmpty()) {
                            course.setCover(UrlUtils.buildFullUrl(request, course.getCover()));
                        }
                        return course;
                    })
                    .collect(Collectors.toList());
                return ResponseEntity.ok(new Result<>(coursesWithFullCoverUrls));
            }else {
                return ResponseEntity.status(500).body(Result.fail(500, "获取课程失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Result.fail(500, "获取课程失败: " + e.getMessage()));
        }
    }

    /**
     * 获取指定课程的所有内容（供移动端使用）
     * @param cid 课程ID
     * @param request HTTP请求对象
     * @return 课程内容列表结果
     */
    @GetMapping("/getAllCourseContent")
    public ResponseEntity<Result<List<CourseContent>>> getAllCourseContent(@RequestParam int cid, HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int userId = JWTUtils.getUserIdFromRequest(request);
            
            // 如果无法获取用户ID，则返回错误
            if (userId == -1) {
                return ResponseEntity.status(401).body(Result.fail(401, "无法获取用户身份信息"));
            }
            
            // 先获取课程信息，以确定所属阶段
            Optional<Course> courseOpt = service.findCourse(cid);
            if (!courseOpt.isPresent()) {
                return ResponseEntity.status(500).body(Result.fail(500, "课程不存在，ID: " + cid));
            }
            
            Course course = courseOpt.get();
            int stageId = course.getCsid();
            
            // 从JWT token中获取用户类型
            String userType = JWTUtils.getUserTypeFromRequest(request);
            boolean isAuthorized = authorizationService.isUserAuthorizedForStage(userId,userType, stageId);

            if (!isAuthorized) {
                return ResponseEntity.status(403).body(Result.fail(403, "未授权访问该课程内容"));
            }
            
            List<CourseContent> datas = service.getAllCourseContent(cid);
            if (datas != null){
                // 为每个课程内容动态构建完整封面URL
                List<CourseContent> contentsWithFullCoverUrls = datas.stream()
                    .map(content -> {
                        if (content.getCover() != null && !content.getCover().isEmpty()) {
                            content.setCover(UrlUtils.buildFullUrl(request, content.getCover()));
                        }
                        List<Audio> audioList = audioRepository.findAllByCourseContentId(content.getId());
                        // 为每个音频动态构建完整URL
                        List<Audio> audiosWithFullUrls = audioList.stream()
                            .map(audio -> {
                                if (audio.getAudio_url() != null && !audio.getAudio_url().isEmpty()) {
                                    audio.setAudio_url(UrlUtils.buildFullUrl(request, audio.getAudio_url()));
                                }
                                return audio;
                            })
                            .collect(Collectors.toList());
                        content.setAudios(audiosWithFullUrls);
                        return content;
                    })
                    .collect(Collectors.toList());
                return ResponseEntity.ok(new Result<>(contentsWithFullCoverUrls));
            }else {
                return ResponseEntity.status(500).body(Result.fail(500, "获取课程内容失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Result.fail(500, "获取课程内容失败: " + e.getMessage()));
        }
    }
}